<template>
  <div>
    <el-card class="box-card" style="margin: 30px 0px">
      <el-button type="primary" size="default" icon="Plus" @click="addTrademark"
        >添加商品</el-button
      >

      <!-- 2.展示表格：border（表格纵向边框）、stripe（斑马纹）、height（固定表头）-->
      <el-table style="margin: 10px 0px" border :data="trademarkArr" stripe height="500">
        <!-- 2.1.每一列：type（显示索引）、默认使用div展示数据，要改变可以用插槽 -->
        <el-table-column label="序号" width="80px" align="center" type="index" />
        <el-table-column label="品名" prop="name" />
        <el-table-column label="数量" prop="quantity" />
        <el-table-column label="价格" prop="price" />
        <el-table-column label="图片">
          <template #="{ row, $index }">
            <img :src="row.image" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="Edit" @click="updateTrademark(row)" />
            <el-popconfirm
              :title="`您确定要删除${row.name}?`"
              width="250px"
              icon="Delete"
              @confirm="removeTradeMark(row.productId)"
            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 3.分页器：布局、页码按钮、选择每页条目、总条目、当前页码、每页条目、
                          做出改变时调用getHasTrademark -->
      <el-pagination
        layout="prev, pager, next, jumper,->,sizes,total"
        :pager-count="9"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        :total="total"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        @change="getHasTrademark"
      />
    </el-card>

    <!-- 4.增改对话框：隐藏/显示 、标题由id决定、
                          表格（绑定数据、校验规则）
                          上传图片：发请求、图片约束（beforeAvatarUpload）、
                                  成功后（handleAvatarSuccess）、显示图片
                          对话框确认、取消按钮-->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.productId ? '修改品牌' : '添加品牌'"
    >
      <el-form style="width: 80%" :model="trademarkParams" :rules="rules" ref="formRef">
        <el-form-item label="品名" label-width="100px" prop="name">
          <el-input placeholder="品名" v-model="trademarkParams.name" />
        </el-form-item>
        <el-form-item label="数量" label-width="100px" prop="quantity">
          <el-input placeholder="数量" v-model="trademarkParams.quantity" />
        </el-form-item>
        <el-form-item label="价格" label-width="100px" prop="price">
          <el-input placeholder="价格" v-model="trademarkParams.price" />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="image">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            action="/api/files/upload"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="trademarkParams.image" :src="trademarkParams.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, UploadProps, formEmits } from 'element-plus'
import { ref, onMounted, reactive, nextTick, watch } from 'vue'
import { pageProducts, selectByName, addProduct, updateProduct, deleteOne } from '@/api/brand/index'

const formRef = ref()
const pageNo = ref<number>(1)
const limit = ref<number>(5)
const total = ref<number>(0)
const trademarkArr = ref([])
const dialogFormVisible = ref<boolean>(false)
//对话框取消
const cancel = () => {
  dialogFormVisible.value = false
}

//组件挂载：获取第一页数据
onMounted(() => {
  getHasTrademark(1, 5)
})

//收集数据
const trademarkParams = reactive({
  productId: '',
  name: '',
  quantity: 0,
  brandId: '',
  price: 0,
  image: '',
  isOnShelf: 0,
})

watch([pageNo, limit], ([newPageNo, newLimit]) => {
  getHasTrademark(newPageNo, newLimit)
})
//传入页码，根据每页条目得到:该页数据、总条目数
const getHasTrademark = async (p: number, l: number) => {
  const result: any = await pageProducts(p, l)
  console.log(result)
  if (result.code == 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.list
    console.log(trademarkArr.value)
  }
}
//添加品牌：对话框显示并完全清空
const addTrademark = () => {
  dialogFormVisible.value = true
  trademarkParams.productId = ''
  trademarkParams.name = ''
  trademarkParams.quantity = 0
  trademarkParams.price = 0
  trademarkParams.image = ''
  formRef.value?.clearValidate('name')
  formRef.value?.clearValidate('image')
}

//修改已有品牌：对话框显示当前数据并清空无效信息
const updateTrademark = (row) => {
  dialogFormVisible.value = true
  trademarkParams.productId = row.productId
  trademarkParams.name = row.name
  trademarkParams.quantity = row.quantity
  trademarkParams.price = row.price
  trademarkParams.image = row.image
  formRef.value?.clearValidate('name')
  formRef.value?.clearValidate('image')
}
//对话框确认：校验表单、操作成功/失败关闭对话框发出提示
const confirm = async () => {
  await formRef.value.validate()
  if (trademarkParams.productId == '') {
    const result: any = await addProduct(trademarkParams)
    if (result.code == 200) {
      dialogFormVisible.value = false
      ElMessage({
        type: 'success',
        message: '添加品牌成功',
      })
      getHasTrademark(pageNo.value, limit.value)
    } else {
      ElMessage({
        type: 'error',
        message: '添加品牌失败',
      })
      dialogFormVisible.value = false
    }
  } else {
    const result: any = await updateProduct(trademarkParams)
    if (result.code == 200) {
      dialogFormVisible.value = false
      ElMessage({
        type: 'success',
        message: '修改品牌成功',
      })
      getHasTrademark(pageNo.value, limit.value)
    } else {
      ElMessage({
        type: 'error',
        message: '修改品牌失败',
      })
      dialogFormVisible.value = false
    }
  }
}

//删除品牌：传id发出请求、成功/失败后提示、显示当前界面
const removeTradeMark = async (id: number) => {
  const temp = id + ''
  const result: any = await deleteOne(temp)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    getHasTrademark(pageNo.value, limit.value)
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}

//品牌名称校验规则
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) callBack()
  else callBack(new Error('品牌名称位数大于等于两位'))
}
//品牌LOGO图片校验规则
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) callBack()
  else callBack(new Error('LOGO图片务必上传'))
}
//校验规则
const rules = {
  name: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  image: [{ required: true, validator: validatorLogoUrl }],
}

//上传图片校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    })
    return false
  }
}

//图片上传成功触发：将图片链接传回便于展示、清除图片校验
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadPic) => {
  trademarkParams.image = response.data
  formRef.value.clearValidate('image')
}
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
